// 检查当前窗口是否为顶级窗口
if (self != top) {
    // 如果不是顶级窗口，则将顶级窗口的 URL 设置为当前窗口的 URL
    top.location.href = self.location.href;
}
$(function () {
    var isValidUsername = false;
    var isValidEmail = false;
    var $loginEmail = $("#login-email");
    var $loginPassword = $("#login-password");
    var $captchaInput = $("#captcha-input");
    var $getVerificationCode = $("#getVerificationCode");
    var $registerAccount = $("#register-account");
    var $registerEmail = $("#register-email");
    var $registerPassword = $("#register-password");

    // 验证码
    var countdown;
    var secondsLeft = 120;


    $("#toLogin").click(function () {
        var rememberMe = $("#remember").is(':checked');
        var tencentKey = "CPJBZ-TQGKN-AFSFU-SMILQ-V4RUV-ZXBAE";
        if ($loginEmail.val() !== "" && $loginPassword.val() !== "") {
            $.ajax({
                url: "https://apis.map.qq.com/ws/location/v1/ip?key=" + tencentKey + "&output=jsonp",
                dataType: "jsonp",
                success: function (res) {
                    var ip = res.result.ip;
                    var {lat, lng} = res.result.location;
                    var {nation, province, city, district, adcode, nationCode} = res.result.ad_info;
                    var jsonData = {
                        ip,
                        location: {lat, lng},
                        adInfo: {nation, province, city, district, adcode, nationCode}
                    };
                    $.ajax({
                        url: "/api/user/toLogin",
                        type: "post",
                        data: {
                            "email": $loginEmail.val(),
                            "password": $loginPassword.val(),
                            "rememberMe": rememberMe
                        },
                        dataType: "json",
                        success: function (res) {
                            if (res.status === 1) {
                                $.ajax({
                                    url: "/api/user/loginInfo",
                                    method: "post",
                                    data: JSON.stringify(jsonData),
                                    contentType: "application/json", // 添加contentType选项
                                    dataType: "json",
                                    success: function (result) {
                                        if (result.status === 1) {
                                            layer.msg(result.message, {icon: 6})
                                            setTimeout(function () {
                                                window.location.href = "/home";
                                            }, 400);
                                        } else {
                                            layer.msg(result.message, {icon: 2})
                                        }

                                    }
                                })
                            } else if (res.status === 0) {
                                layer.msg(res.message, {icon: 5})
                                $loginPassword.val("")
                                $loginPassword.focus()
                            } else if (res.status === 2) {
                                layer.msg(res.message, {icon: 2})
                            }
                        }, error: function () {
                            layer.msg("登录失败！请联系管理员 <a href=\"mailto:xb.yang1@outlook.com\">点击这里发送邮件给xb.yang1@outlook.com</a>", {icon: 2})
                        }
                    })
                }, error: function () {
                    alert("登录失败，请检查你的网络！");
                }
            })

        } else {
            layer.msg("不能为空！", {icon: 4})
        }
    })
    $.ajax({
        url: "/api/role/getAllRole",
        method: "post",
        dataType: "json",
        success: function (res) {
            if (res.status === 1) {
                var dom = "";
                for (var i = 0; i < res.data.length; i++) {
                    dom += "<option value='" + res.data[i].id + "'>" + res.data[i].remark + "</option>"
                }
                $("#roles").append(dom).attr("size", res.data.length + 1)
            } else {
                layer.msg(res.message, {icon: 5})
            }
        }, error: function () {
            layer.msg("请联系管理员 <a href=\"mailto:xb.yang1@outlook.com\">点击这里发送邮件给xb.yang1@outlook.com</a>", {icon: 2})
        }
    })
    $registerAccount.blur(function () {
        $.ajax({
            url: "/api/user/checkRegisterAccount",
            method: "post",
            data: {"account": $("#register-account").val()},
            dataType: "json",
            success: function (res) {
                $registerAccount.css("color", res.status !== 1 ? "red" : "white");
                isValidUsername = res.status === 1;
            }
        })
    })

    $registerEmail.blur(function () {
        $.ajax({
            url: "/api/user/checkRegisterEmail",
            method: "post",
            data: {"email": $registerEmail.val()},
            dataType: "json",
            success: function (res) {
                $registerEmail.css("color", res.status !== 1 ? "red" : "white");
                isValidEmail = res.status === 1;
            }
        })
    })

    $("#toRegister").click(function () {
        // layer.msg("你没有该权限 请联系管理员 <a href=\"mailto:xb.yang1@outlook.com\">点击这里发送邮件给xb.yang1@outlook.com</a>", {icon: 2})
        // return;
        var username = $registerAccount.val();
        var email = $registerEmail.val();
        var captcha = $captchaInput.val();
        var password = $registerPassword.val();
        var selectedValue = $("#roles").val();

        if (!isValidUsername || !isValidEmail) {
            alert("数据不合法！");
            return;
        }

        if (password.length < 6) {
            alert("密码不得低于6位！");
            $registerPassword.focus();
            return;
        }

        if (selectedValue.length === 0) {
            alert("请选择角色");
            return;
        }

        if (captcha.length !== 4) {
            alert("请输入正确的验证码");
            $registerPassword.focus();
            return;
        }

        $.ajax({
            url: "/api/user/register",
            method: "post",
            data: {
                "username": username,
                "email": email,
                "password": password,
                "validateCode": captcha,
                "selectedValue": selectedValue.toString()
            },
            dataType: "json",
            success: function (res) {
                layer.msg(res.message, {icon: -1})
                if (res.status === 1) {
                    setTimeout(function () {
                        window.location.reload()
                    }, 400);
                }
            }
        });
    });

    // 验证码
    function disableButton() {
        $getVerificationCode.prop("disabled", true);
    }

    function enableButton() {
        $getVerificationCode.prop("disabled", false).html("重新获取");
    }

    function updateButtonText() {
        $getVerificationCode.html(secondsLeft + "秒后重新获取");
    }

    function countdownTimer() {
        secondsLeft--;

        if (secondsLeft === 1) {
            updateButtonText();
        }

        if (secondsLeft <= 0) {
            clearInterval(countdown);
            enableButton();
        } else {
            updateButtonText();
        }
    }

    function startCountdown() {
        disableButton();
        secondsLeft = 120;
        countdown = setInterval(countdownTimer, 1000);
    }

    $getVerificationCode.click(function () {
        var email = $registerEmail.val();
        var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        var validEmail = emailPattern.test(email);
        if (!validEmail) {
            alert("邮箱不合法！")
            return;
        }
        if (!isValidEmail) {
            alert("此邮箱已存在")
            return
        }

        if (validEmail) {
            $.ajax({
                url: "/sendEmail",
                method: "post",
                data: {"email": email},
                dataType: "json",
                success: function (res) {
                    if (res.status === 1) {
                        startCountdown();
                    }
                    layer.msg(res.message, {icon: res.status === 1 ? 1 : res.status === 0 ? 2 : 7});
                }
            });
        }
    });

    $captchaInput.on("keypress", function (event) {
        var charCode = event.charCode;
        // 检查是否为数字键
        if (charCode < 48 || charCode > 57) {
            event.preventDefault();
        }
    });

})

// 要操作到的元素
let login = document.getElementById('login');
let register = document.getElementById('register');
let form_box = document.getElementsByClassName('form-box')[0];
let register_box = document.getElementsByClassName('register-box')[0];
let login_box = document.getElementsByClassName('login-box')[0];
// 去注册按钮点击事件
register.addEventListener('click', () => {
    form_box.style.transform = 'translateX(80%)';
    login_box.classList.add('hidden');
    register_box.classList.remove('hidden');
})
// 去登录按钮点击事件
login.addEventListener('click', () => {
    form_box.style.transform = 'translateX(0%)';
    register_box.classList.add('hidden');
    login_box.classList.remove('hidden');
})

// 不让用户输入空格
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
    inputs[i].addEventListener('keydown', function (event) {
        if (event.key === ' ') {
            event.preventDefault();
        }
    });

    inputs[i].addEventListener('input', function () {
        this.value = this.value.replace(/\s/g, '');
    });
}

function admin() {
    var userInput = prompt("1+1=?"); // 弹出输入框

    // 检查用户输入是否与设置的内容一样
    if (userInput === "123") {
        // 如果输入一样，执行下一步操作
        // TODO: 在这里添加你的下一步操作代码
        $("#login-email").val("xb.yang1@outlook.com")
        $("#login-password").val("123")
        $("#toLogin").click();
        layer.msg("欢迎你", {icon: -1})
    } else {
        // 如果输入不一样，给出错误提示
        layer.msg("你是哪个？", {icon: -1})
    }

}